package com.gxuwz.stats.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.AchievementTransfer;
import com.gxuwz.stats.service.AchievementTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/achievementTransfer")
public class AchievementTransferController {

    @Autowired
    private AchievementTransferService service;

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {

        try {
            IPage<AchievementTransfer> page = new Page<>(currentPage, pageSize);
            QueryWrapper<AchievementTransfer> wrapper = new QueryWrapper<>();

            if (params.containsKey("keyword") && !params.get("keyword").isEmpty()) {
                String keyword = params.get("keyword");
                wrapper.and(w -> w.like("transfer_achievement_name", keyword)
                        .or().like("user_id", keyword)
                        .or().like("transfer_type", keyword));
            }

            IPage<AchievementTransfer> result = service.page(page, wrapper);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", result.getRecords());
            response.put("total", result.getTotal());
            response.put("currentPage", result.getCurrent());
            response.put("pageSize", result.getSize());
            response.put("totalPages", result.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> add(@RequestBody AchievementTransfer entity) {
        try {
            boolean result = service.save(entity);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", result ? "新增成功" : "新增失败"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("code", 500, "message", "新增失败: " + e.getMessage()));
        }
    }

    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> update(@RequestBody AchievementTransfer entity) {
        try {
            boolean result = service.updateById(entity);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", result ? "修改成功" : "修改失败"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("code", 500, "message", "修改失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> delete(@RequestBody List<Integer> ids) {
        try {
            boolean result = service.removeByIds(ids);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", result ? "删除成功" : "删除失败"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("code", 500, "message", "删除失败: " + e.getMessage()));
        }
    }

    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "false") boolean updateSupport) {
        try {
            List<AchievementTransfer> list = service.importExcel(file, updateSupport);
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", "导入成功",
                    "data", list
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("code", 400, "message", "导入失败: " + e.getMessage()));
        }
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportExcel(@RequestParam(required = false) String keyword) {
        try {
            byte[] excelBytes = service.exportExcel(keyword);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=achievement_transfer.xlsx")
                    .header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .body(excelBytes);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}